package com.zxx.dis.service;

import com.zxx.dis.core.DistributedLockFactory;
import com.zxx.dis.factory.DistributedLockFactoryCreator;
import com.zxx.dis.factory.RedisDistributedLockFactory;
import com.zxx.dis.lock.DistributedRedisLock;
import com.zxx.dis.lock.RedisReentrantLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Service
public class StockService {
    private final DistributedLockFactoryCreator distributedLockFactoryCreator;
    private final StringRedisTemplate stringRedisTemplate;


    @Autowired
    private StockService(DistributedLockFactoryCreator distributedLockFactoryCreator, StringRedisTemplate stringRedisTemplate) {
        this.distributedLockFactoryCreator = distributedLockFactoryCreator;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public int deduct() throws InterruptedException {
        DistributedLockFactory redisDistributedLockFactory = distributedLockFactoryCreator.getFactory("redis");
        Lock lock = redisDistributedLockFactory.createLock("lock");
        lock.lock();
        try {
            String stockValue = stringRedisTemplate.opsForValue().get("stock");
//            TimeUnit.SECONDS.sleep(1000);
            reentrytest();
            System.out.println(stockValue);
            if (stockValue == null) {
                return -1; // 或者抛出异常，表示库存不存在
            }
            int stock = Integer.parseInt(stockValue);

            if (stock > 0) {
                stock--;
                stringRedisTemplate.opsForValue().set("stock", String.valueOf(stock));
                return stock;
            } else {
                return 0; // 或者抛出异常，表示库存不足
            }
        } finally {
            lock.unlock();
        }
    }

    public void reentrytest() throws InterruptedException {
        DistributedLockFactory redisDistributedLockFactory = distributedLockFactoryCreator.getFactory("redis");
        Lock lock = redisDistributedLockFactory.createLock("lock");
        lock.lock();
        System.out.println("reentrytest success");
//        Thread.sleep(50);
        lock.unlock();
    }

}
